<?php

namespace app\modules\admin\models;

use Yii;
use yii\base\Model;
use yii\rbac\Rule;

/**
 * This is the model class for table "hs_auth_rule".
 * @property bool isNewRecord
 * @property Rule item
 */
class AuthRule extends Model
{
	/**
	 * @var string name of the rule
	 */
	public $name;
	/**
	 * @var string|Rule classname
	 */
	public $className;
	/**
	 * @var Rule
	 */
	private $_item;

	/**
	 * AuthRule constructor.
	 * @param Rule $item
	 * @param array $config
	 */
	public function __construct($item = null, $config = [])
	{
		$this->_item = $item;
		if($item !== null) {
			$this->name = $item->name;
			$this->className = get_class($item);
		}
		parent::__construct($config);
	}

	/**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'className'], 'required'],
            [['name', 'className'], 'string'],
			[['className'], 'classExists'],
        ];
    }

	/**
	 * 说明: 类名验证
	 * @return bool
	 */
	public function classExists() {
    	if(!class_exists($this->className)) {
    		$message = sprintf('未知的类名： \'%s\'', $this->className);
    		$this->addError('className', $message);
    		return false;
		}
		if(!is_subclass_of($this->className, Rule::className())) {
    		$message = sprintf('类 \'%s\'" 必须继承自 \'yii\\rbac\\Rule\' 或者是它的子类', $this->className);
    		$this->addError('className', $message);
		}
		return false;
	}
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => '规则名称',
            'className' => '规则类名',
        ];
    }

    public function getIsNewRecord() {
    	return $this->_item === null;
	}

	/**
	 * 说明: 通过名称查找规则
	 * @param $id
	 * @return null|static
	 */
	public static function find($id) {
    	$item = Yii::$app->authManager->getRule($id);
    	if($item !== null) {
    		return new static($item);
		}
		return null;
	}

	/**
	 * 说明: 保存规则
	 * @return bool
	 */
	public function save() {
		if($this->validate()) {
			$mgr = Yii::$app->authManager;
			$class = $this->className;
			if($this->isNewRecord()) {
				$this->_item = new $class();
				$this->_item->name = $this->name;
				$mgr->add($this->_item);
			} else {
				$oldName = $this->_item->name;
				$this->_item->name = $this->name;
				$mgr->update($oldName, $this->_item);
			}
			return true;
		}
		return false;
	}

	/**
	 * 说明: Get Item
	 * @return Rule
	 */
	public function getItem() {
		return $this->_item;
	}
}
